//
//  WBPictureView.swift
//  SinaWeibo
//
//  Created by zhuangqianwei on 16/11/17.
//  Copyright © 2016年 zhuangqianwei. All rights reserved.
//

import UIKit
private let cellId = "pictureCellId"

class WBPictureView: UICollectionView {

    
        
        var pictureInfos: [WBPictureInfo]?{
        
        didSet{
            //外界给配图视图设置数据的时候就会执行
            
            self.reloadData()
     }
}
        override func awakeFromNib(){
           //注册cell
            let pictureCellNib = UINib(nibName: "WBPictureCollectionCell", bundle: nil)
            
            self.register(pictureCellNib, forCellWithReuseIdentifier: cellId)
            self.delegate = self
            self.dataSource = self
        }
}
extension WBPictureView : UICollectionViewDataSource,UICollectionViewDelegate {
    //实现数据源方法
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictureInfos?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! WBPictureCollectionCell
        let pictureInfo = self.pictureInfos![indexPath.item]
        cell.pictureInfo = pictureInfo
        return cell
    }

    //实现代理方法
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        //实力化图片浏览器对象
        let borwser = SDPhotoBrowser()
        //设置容器视图  父视图
        borwser.sourceImagesContainerView = self
        borwser.currentImageIndex = indexPath.item
        borwser.imageCount = pictureInfos?.count ?? 0
        //设置代理
        borwser.delegate = self
        //设置图片浏览器
        borwser.show()
    }

}

extension WBPictureView: SDPhotoBrowserDelegate {
    
    func photoBrowser(_ browser: SDPhotoBrowser!, highQualityImageURLFor index: Int) -> URL! {
        let picinfo = self.pictureInfos![index]
        let url = URL(string: picinfo.bimiddleImage ?? "")
        return url
    }
    
     func photoBrowser(_ browser: SDPhotoBrowser!, placeholderImageFor index: Int) -> UIImage! {
        //返回一个占位图片
        //获取cell
        let indexPath = IndexPath(item: index, section: 0)
        let cell = self.cellForItem(at: indexPath) as? WBPictureCollectionCell
        return cell?.Img_picture.image
    }

    }
    
    
    






